﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace Patchworker
{
	public partial class MainWindow : Form
	{
		MainCanvas mainCanvas;

		String fileDirectory;
		String safeFileName;

		AnimationPreviewWindow previewWindow;

		public MainWindow()
		{
			InitializeComponent();
			initToolStripHandlers();
			mainCanvas = new MainCanvas(this.ImagePanel);

			previewWindow = new AnimationPreviewWindow();

			ImagePanel.Invalidated += new InvalidateEventHandler(ImagePanel_Invalidated);


			ImagePanel.Paint += new PaintEventHandler(ImagePanel_Paint);
		}

		void ImagePanel_Paint(object sender, PaintEventArgs e)
		{
			Graphics g = e.Graphics;

			g.Clear(ConfigContainer.Instance.BackgroundColor);

				if (ConfigContainer.Instance.RenderBackgroundImage)
				{
					if (ConfigContainer.Instance.BackgroundImage != null)
						g.DrawImage(ConfigContainer.Instance.BackgroundImage, 0, 0, ConfigContainer.Instance.BackgroundImage.Width, ConfigContainer.Instance.BackgroundImage.Height);
				}

			mainCanvas.render(e.Graphics);
		}

		#region initialize
		private void MainWindow_Load(object sender, EventArgs e)
		{
			initializeForms();
		}

		private void initializeForms()
		{
			previewWindow.Close();
			previewWindow.IsPlaying = false;

			TileSizeLabel.Text = "";

			ConfigContainer.Instance.BackgroundColor = BackgroundColorButton.ForeColor;

			mainCanvas.ShowTile = ShowTileCheckBox.Checked;

			this.TilesGroupBox.Visible = false;
			this.AnimationButton.Enabled = false;
			this.ExportButton.Enabled = false;

			ConfigContainer.Instance.NumHorizontalGrids = 1;
			ConfigContainer.Instance.NumVerticalGrids = 1;
			HorNumTileBox.Value = 1;
			VerNumTileBox.Value = 1;
		}

		#endregion



		void ImagePanel_Invalidated(object sender, InvalidateEventArgs e)
		{
			foreach (Control control in ImagePanel.Controls)
			{
				control.Invalidate();
			}
			
		}

	

		private void refreshInformations(Image image)
		{
			SizeLabel.Text = image.Width + " X "+image.Height;
			PixelFormatLabel.Text = image.PixelFormat.ToString();
		}

		private void calcTileSize(Image image)
		{
			if (image != null)
			{
				int hor = (int)(image.Width / (int)HorNumTileBox.Value);
				int ver = (int)(image.Height / (int)VerNumTileBox.Value);

				this.TileSizeLabel.Text = hor + " X " + ver;

				/*
				//타일사이즈가 정확히 나누어지지 않을 때
				if (image.Width % HorNumTileBox.Value != 0 || image.Height % VerNumTileBox.Value != 0)
				{
					TileSizeErrorTextBox.Text = "이미지 사이즈가 타일 사이즈로 정확히 나누어 떨어지지 않습니다.";
				}
				else TileSizeErrorTextBox.Text = "";
				 * */

			}
		}

		private void BackgroundColorButton_Click(object sender, EventArgs e)
		{
			ColorDialog.ShowDialog();

			this.BackgroundColorButton.ForeColor = ColorDialog.Color;

			ConfigContainer.Instance.BackgroundColor = ColorDialog.Color;
		}

		private void NumTileBox_ValueChanged(object sender, EventArgs e)
		{
			if (ConfigContainer.Instance.Mode == ETileMode.Split)
			{
				calcTileSize(ConfigContainer.Instance.Atlas);

				ConfigContainer.Instance.initTileSize((int)HorNumTileBox.Value, (int)VerNumTileBox.Value);
			}
			else
			{
				ConfigContainer.Instance.NumHorizontalGrids = (int)HorNumTileBox.Value;

				TileSizeLabel.Text = ConfigContainer.Instance.Atlas.Size.Width + " X " + ConfigContainer.Instance.Atlas.Size.Height;
			}
		}

		private void ShowTileCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			mainCanvas.ShowTile = ShowTileCheckBox.Checked;
		}

		private void export_Click(object sender, EventArgs e)
		{

			String[] fileNameCut = safeFileName.Split(new char[] { '.' });
			String fileName = fileNameCut[0];


			if (ConfigContainer.Instance.Mode == ETileMode.Split)
			{
				if (ConfigContainer.Instance.Atlas != null)
				{
					Bitmap[] tiles = mainCanvas.TileBitmaps;


					String saveFolderName = fileName + "_tiled";

					int numbering = 0;

					while (Directory.Exists(fileDirectory + saveFolderName))
					{
						saveFolderName = fileName + "_tiled_" + numbering;

						numbering++;
					}

					String tileDirectory = fileDirectory + saveFolderName + @"\";

					Directory.CreateDirectory(tileDirectory);

					for (int i = 0; i < tiles.Length; i++)
					{
						String finalURL = tileDirectory + fileName + "_tiled_" + i + "." + fileNameCut[1];
						tiles[i].Save(finalURL);
					}

					System.Diagnostics.Process.Start(tileDirectory);
				}
			}
			else
			{
				Bitmap atlasBitmap = new Bitmap(ConfigContainer.Instance.Atlas);
				
				String atlasFileName = fileName + "_atlas.png";

				int numbering = 0;

				while (File.Exists(fileDirectory + atlasFileName))
				{
					atlasFileName = fileName + "_atlas" + numbering + ".png";
				}

				atlasBitmap.Save(fileDirectory + atlasFileName);

				System.Diagnostics.Process.Start(fileDirectory);

			}
		}

		private void AnimationButton_Click(object sender, EventArgs e)
		{
			previewWindow.Show();
			previewWindow.Focus();
		}

		private void BackgroundImageCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			ConfigContainer.Instance.RenderBackgroundImage = BackgroundImageCheckBox.Checked;
		}

		private void loadBackgroundImage(String url)
		{
			ConfigContainer.Instance.BackgroundImage = Image.FromFile(url);
			this.BackgroundImageCheckBox.Checked = true;
		}

		private void BackgroundButton_Click(object sender, EventArgs e)
		{
			OpenBGDialog.ShowDialog();
		}
		private void OpenBGDialog_FileOk(object sender, CancelEventArgs e)
		{
				this.BGURLTextbox.Text = OpenBGDialog.FileName;

				loadBackgroundImage(OpenBGDialog.FileName);
		}

	}
}
